<template>
  <div class="reset-password-box">
    <el-form
      ref="form"
      :model="formData"
      :rules="rules"
      label-width="80px"
      class="flex flex-wrap"
    >
      <template v-for="item in formList">
        <el-form-item
          :key="item.prop"
          :label="item.name"
          :prop="item.prop"
          :class="item.itemClass"
          :style="{ width: item.width }"
        >
          <component
            :is="item.componentType || 'el-input'"
            v-model="formData[item.prop]"
            :clearable="true"
            :disabled="handleDisabled(item)"
            v-bind="item.attrConfig || {}"
          >
            <span v-if="item.componentType === 'span'">{{
              formData[item.prop]
            }}</span>
          </component>
        </el-form-item>
      </template>
    </el-form>
  </div>
</template>

<script>
import { encryptByMd5 } from '@/utils/index'
export default {
  name: 'ResetPassword',
  props: {
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        userName: '',
        password: '',
        passwordConfirm: ''
      },
      formList: [
        {
          name: '用户名',
          prop: 'userName',
          width: '100%',
          attrConfig: { disabled: true, autocomplete: 'off' }
        },
        {
          name: '密码',
          prop: 'password',
          width: '50%',
          attrConfig: {
            type: 'password',
            'show-password': true,
            placeholder: '请输入新密码',
            autocomplete: 'new-password'
          }
        },
        {
          name: '确认密码',
          prop: 'passwordConfirm',
          width: '50%',
          attrConfig: {
            type: 'password',
            'show-password': true,
            placeholder: '请输入确认密码'
          }
        }
      ]
    }
  },
  computed: {
    handleDisabled() {
      return (item) => {
        if (item.prop === 'passwordConfirm') {
          return !this.formData.password
        }
        if (item.prop === 'userName') {
          return true
        }
        return false
      }
    },
    rules() {
      return {
        password: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          { required: true, trigger: 'blur', validator: this.passwordValidate }
        ],
        passwordConfirm: [
          { required: true, message: '请输入确认密码', trigger: 'blur' },
          {
            required: true,
            trigger: 'blur',
            validator: this.passwordConfirmValidate
          }
        ]
      }
    }
  },
  watch: {
    popData: {
      handler(data) {
        if (data) {
          this.$set(this.formData, 'userName', data.userName)
        }
      },
      deep: true,
      immediate: true
    },
    confirm() {
      const params = {
        id: this.popData.id,
        password: this.formData.password
      }
      this.submit(params)
    }
  },
  methods: {
    /**
     * 提交
     */
    submit(params) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const MD5Password = encryptByMd5(params.password)
          const res = await this.$api.userManage.resetPassword({
            ...params,
            password: MD5Password
          })
          if (Number(res.code) === 1000) {
            this.$message.success('重置成功!')
            this.$emit('onFinish', 'reset-password')
          } else if (res.msg) {
            this.$message({ type: 'error', message: res.msg })
          }
        }
      })
    },
    /**
     * 验证密码
     */
    passwordValidate(rule, value, callback) {
      //  密码正则，8到18位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符
      // const REP = new RegExp(/^.*(?=.{8, 18})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/)
      // 密码正则，8到18位，包括至少1个字母，1个数字
      const REP = new RegExp(/^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z]).*$/)
      if (!REP.test(value)) {
        callback(new Error('您的密码格式有误!'))
      } else {
        callback()
      }
    },
    /**
     * 验证确认密码
     */
    passwordConfirmValidate(rule, value, callback) {
      const { password } = this.formData || {}
      //  密码正则，8到18位，包括至少1个大写字母，1个小写字母，1个数字，1个特殊字符
      // const REP = new RegExp(/^.*(?=.{8, 18})(?=.*\d)(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*? ]).*$/)
      // 密码正则，8到18位，包括至少1个字母，1个数字
      const REP = new RegExp(/^.*(?=.{8,})(?=.*\d)(?=.*[a-zA-Z]).*$/)
      if (!REP.test(value)) {
        callback(new Error('您的密码格式有误!'))
      } else if (password !== value) {
        callback(new Error('密码不一致'))
      } else {
        callback()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.reset-password-box {
  color: #333;
  padding: 0 20px;
}
</style>
